<template>
  <el-button v-bind="$attrs" :disabled="disabled" :type="type" @click="onCopy">
    <input style="opacity: 0;position: absolute;left: -9999px;" ref="copy" v-model="value"/>
    <slot>复制</slot>
  </el-button>
</template>
<script>
import $msgBox from '@/utils/src/message-box'

export default {
  inheritAttrs: false,
  name: 'CCopy',
  props: {
    disabled: Boolean,
    text: String,
    successMsg: {
      type: String,
      default () {
        return '复制成功'
      }
    },
    failedMsg: {
      type: String,
      default () {
        return '浏览器不支持该功能，请手动复制'
      }
    },
    type: {
      type: String,
      default () {
        return 'text'
      }
    }
  },
  data () {
    return {
      value: this.text
    }
  },
  watch: {
    text (v) {
      this.value = v
    },
    value (v) {
      if (v !== this.text) {
        this.value = this.text
      }
    }
  },
  methods: {
    onCopy () {
      this.value = this.text
      this.$refs['copy'].select()
      if (document.execCommand('Copy')) {
        $msgBox.success(this.successMsg)
      } else {
        this.$alert(this.text, this.failedMsg)
      }
    }
  }
}
</script>
